from funasr import AutoModel

from interview_voice_project.common import config_ini, get_logger
logger = get_logger(__name__)
try:
    import torch
    _cuda_available = torch.cuda.is_available()
except Exception:
    _cuda_available = False

_device = (config_ini.VOICE_MODEL.DEVICE or "cpu").strip()
_chosen_device = "cuda" if _device.lower() == "cuda" and _cuda_available else "cpu" if _device.lower() == "cuda" and not _cuda_available else _device
_vad_max = int((config_ini.VOICE_MODEL.VAD_MAX_SINGLE_SEGMENT_TIME or "60000").strip())

try:
    my_voice_model = AutoModel(
        model=config_ini.VOICE_MODEL.SVS_MODEL_PATH,
        trust_remote_code=True,
        vad_model=config_ini.VOICE_MODEL.SFVZC_MODEL_PATH,
        vad_kwargs={"max_single_segment_time": _vad_max},
        device=_chosen_device,
        disable_update=True
    )
    logger.info(f"voice_model_loaded: device={_chosen_device}, vad_max={_vad_max}")
except Exception:
    my_voice_model = AutoModel(
        model=config_ini.VOICE_MODEL.SVS_MODEL_PATH,
        trust_remote_code=True,
        vad_model=config_ini.VOICE_MODEL.SFVZC_MODEL_PATH,
        vad_kwargs={"max_single_segment_time": _vad_max},
        device="cpu",
        disable_update=True
    )
    logger.info("voice_model_loaded: device=cpu_fallback")

def get_asr_device():
    return _chosen_device
